Find the Duplicate Number

问题描述(难度简单)

Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

Example 1:

1
2
Input: [1,3,4,2,2]
Output: 2

Example 2:

1
2
Input: [3,1,3,4,2]
Output: 3

Note:

  1. You must not modify the array (assume the array is read only).
  2. You must use only constant, O(1) extra space.
  3. Your runtime complexity should be less than O(n2).
  4. There is only one duplicate number in the array, but it could be repeated more than once.

方法一:排序

时间复杂度Nlog(N),空间复杂度O(1)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package P287;

import java.util.Arrays;

/**
* @autor yeqiaozhu.
* @date 2019-10-21
*/
public class UsingSort {

public int findDuplicate(int[] nums) {
Arrays.sort(nums);
for (int i = 0; i < nums.length-1; i++) {
if (nums[i]==nums[i+1]) {
return nums[i];
}
}
return 0;
}

public static void main(String[] args) {
int[] ints={1,3,4,2,2};
new UsingSort().findDuplicate(ints);
}
}

方法二:哈希Set

时间复杂度O(1),空间复杂度O(N)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package P287;

import java.util.HashSet;
import java.util.Set;

/**
* @autor yeqiaozhu.
* @date 2019-10-18
*/
public class UsingHashSet {
public int findDuplicate(int[] nums) {
Set<Integer> set=new HashSet<>();
for (int i = 0; i < nums.length; i++) {
if (set.contains(nums[i])) {
return nums[i];
}
set.add(nums[i]);
}
return 0;
}

public static void main(String[] args) {
int[] ints={1,3,4,2,2};
new UsingHashSet().findDuplicate(ints);
}
}

方法三:快慢指针

难理解,先摘录。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public int findDuplicate(int[] nums) {
int fast = 0, slow = 0;
while(true){
fast = nums[nums[fast]];
slow = nums[slow];
if(fast == slow)
break;
}
int finder = 0;
while(true){
finder = nums[finder];
slow = nums[slow];
if(slow == finder)
break;
}
return slow;
}